<?php


namespace App\HttpController\Admin;
use App\HttpController\Base as BaseBase;
use App\Model\Config;
use App\Util\Common;
use App\Util\SystemErr;
use EasySwoole\EasySwoole\ServerManager;

class Base extends BaseBase
{
    protected function onRequest(?string $action): ?bool
    {
        if( parent::onRequest( $action )) {
            $host = $this->request()->getHeaderLine('host');
            $adm_host = parse_url(ADM_HOST)['host'];
            if($host != $adm_host){
                $fd = $this->request()->getSwooleRequest()->fd;
                ServerManager::getInstance()->getSwooleServer()->close($fd);
                return false;
            }
            $url = Common::getRequestUri($this->request());
            $withOutUrl = ['admin/login','admin/login/logout' ];
            if(  !in_array($url,$withOutUrl)  ) {
                $token = $this->request()->getHeaderLine('x-token');
                if( !$token)  {
                    $this->argError('未登录');
                    return false;
                } else {
                    $uid = \App\Logic\Login::getUserData($token,'id');
                    if(!$uid) {
                        $this->argError('未登录或已失效！');
                        return false;
                    }
                    $this->request()->withHeader('user_id', $uid);
                }
                $user_roleArr = Common::redis()->sIsMember(REDIS_ADMIN_USER_ROLE . $token, $url);
                if( $user_roleArr !== 1){
                    $this->argError('没有操作权限！',203);
                    return false;
                }
                return true;
            }

            return true; // TODO: Change the autogenerated stub
        }
        return false;

    }

    protected function lay( array $arr, ? int $rows = 0)
    {
        $re['code'] = 0;
        $re['data'] = $arr;
        if($rows && $rows >= 1)
        {
            $re['count'] = $rows;
        }
        $this->response()->write(\json_encode($re, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        $this->response()->withHeader('Content-type', 'application/json;charset=utf-8');
        $this->response()->withStatus(200);

    }

    protected function onException(\Throwable $e): void
    {
        $is_debug = Config::create()->myGet('is_admin_debug');
        $erMsg = $e->getMessage() . ' at ' .$e->getFile() . ' in ' . $e->getLine();
        if($is_debug == 'y' ||  $e->getCode() == 401) {
            $errMsg = $erMsg;
        } else {
            $errMsg = '系统错误！';
        }
        if( $e->getCode() != '401'){
            SystemErr::write($e,'[后台]');
        }

        $this->argError($errMsg,$e->getCode() ?? 404);
    }

}